package org.meteorshower.config;

import org.meteorshower.domain.Renter;
import org.meteorshower.service.IRenterService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;


public class RenterAuthenticationProvider implements AuthenticationProvider {


    private IRenterService renterService;
    private PasswordEncoder passwordEncoder;

    public RenterAuthenticationProvider(IRenterService adminService) {
        this(adminService,null);
    }

    public RenterAuthenticationProvider(IRenterService renterService, PasswordEncoder encoder) {
        this.renterService = renterService;
        this.passwordEncoder = encoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        RenterAuthenticationToken renterAuthenticationToken;
        if (supports(authentication.getClass())){
            renterAuthenticationToken = (RenterAuthenticationToken) authentication;
        }else {
            throw new BadCredentialsException("不支持的认证方式");
        }
        String requestUsername = (String) renterAuthenticationToken.getPrincipal();
        String requestPassword = (String) renterAuthenticationToken.getCredentials();
        String rid = renterAuthenticationToken.getRId();
        Renter renter = (Renter) renterService.loadUserByUsername(requestUsername);
        if (renter == null){
            throw new BadCredentialsException("用户不存在");
        }
        if (!renter.getRoomId().getId().equals(Integer.parseInt(rid))){
            throw new BadCredentialsException("用户不在房间"+ rid + "中");
        }
        boolean condition;
        if (passwordEncoder == null) {
            condition = renter.getPassword().equals(requestPassword);
        }else{
            condition = passwordEncoder.matches(requestPassword,renter.getPassword());
        }
        if (condition){
            //认证通过密码置空
            return new RenterAuthenticationToken(renter.getUsername(),null,rid,renter.getAuthorities());
        }else{
            throw new BadCredentialsException("密码错误");
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return RenterAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
